Previous | Next | Trail Map | Creating a User Interface | Table of Contents


Laying Out Components within a Container


Above are pictures of two programs, each of which displays five buttons. The Java code for both programs is almost identical. So why do they look so different? Because they use different layout managers to control the layout of the buttons.

A layout manager is an object that controls the size and position of components in a container. Layout managers adhere to the LayoutManager interface. By default, every Container object has a LayoutManager object that controls its layout. For Panel objects, the default layout manager is an instance of the FlowLayout class. For Window objects, the default layout manager is an instance of the BorderLayout class.

This lesson tells you how to use the layout managers the AWT provides. It also shows you how to write your own layout manager. It even tells you how to do without a layout manager by specifying components' absolute positions and sizes. Finally, this lesson discusses some common layout problems and their solutions.

Using Layout Managers

Here's where to learn how to use layout managers. This section gives both general rules and detailed instructions on using each of the layout managers the AWT provides.

Creating a Custom Layout Manager

Instead of using one of the AWT's layout managers, you can write your own. Layout managers must implement the LayoutManager interface, which specifies the five methods every layout manager must define.

Doing Without a Layout Manager (Absolute Positioning)

You can position components without using a layout manager. Generally, this solution is used to specify absolute positions for components, and only for applications that are executed on only one platform. Absolute positioning is often unsuitable for applets and other platform-independent programs, since the size of components can be different on different platforms.

Common Layout Problems (and Their Solutions)

Some of the most common layout problems are that components are displayed too small -- or not at all. This section tells you how to fix these and other common layout problems.


Previous | Next | Trail Map | Creating a User Interface | Table of Contents